import pymysql as SQL
import urllib.parse as urlParse
import re
def killAnUnseen(s):
	# "删除一个url编码中在一般中文编码不可见、不能对应的西文字符"
    try:
        f = open('kill.html', 'w');
        f.write(s);
        f.close()
    except UnicodeEncodeError as err:
        info = str(err);
        st = re.search('\\\\U[a-f0-9]{8}|\\\\u[a-f0-9]{4}|\\\\x[a-f0-9]{2}', info).group()[2:];
        x = int(st, 16);
        return (s.replace(chr(x), ""), True)
    return s, False

def killUnseen(s):
	# 处理一个字符串中的不可见西文字符
	# s：待处理字符串
    s = s.replace("+","")
    while(True):
        s, res = killAnUnseen(s)
        if res == False:
            return s

connect=SQL.connect(host='localhost',port=3305,user='root',passwd='admin',db='httpdata',use_unicode=True,charset='utf8')
cur=connect.cursor()



def getGood(tb,fld,where=''):
	"""
	获得数据库中的正常参数值
	tb：存储参数值的数据表
	fld：要获得的参数名
	where：限制性语句
	"""
	rst=[]
	sql='select distinct '+fld+' from '+tb+'  '+where 
	cur.execute(sql)
	temp=cur.fetchall()
	for x in temp:
		rst.append(urlParse.unquote(killUnseen(urlParse.unquote(x[0]))))
	return rst
def getBad(tb='badsupplement',fld='badValue',where=''):
	"""
	获得数据库中的异常参数值
	tb：存储参数值的数据表，默认 badsupplement
	fld：要获得的参数名，默认badValue（因为采用的的收集的各种payload）
	where：限制性语句
	"""
	rst=[]
	sql='select distinct '+fld+' from '+tb+'  '+where 
	cur.execute(sql)
	temp=cur.fetchall()
	for x in temp:
		rst.append(urlParse.unquote(killUnseen(urlParse.unquote(x[0]))))
	return rst
def getAllColumnName(targetTableName):
	"""
	获得目标数据表中的所有字段名称，仅限于mysql数据库
	"""
	rst = []
	sql = "select distinct column_name from information_schema.columns where table_name = '"+targetTableName+"'"
	print(sql)
	cur.execute(sql)
	temp = cur.fetchall()
	for x in temp:
		rst.append(x[0])
	return rst


if __name__ == '__main__':
	# print("good:",getGood('normalparams','email',where=' limit 2,26'))
	# print(getBad(where=' limit 2,26'))
	# print(getAllColumnName('NORMALPARAMS'))
	bad = getBad(where=' limit 2,260')
	for x in bad:
		print(urlParse.unquote(x))